<template>
  <div>
    <el-dialog v-model="dialogVisible" title="短信群发" width="30%">
      <el-form ref="smsFormRef" :model="smsForm" label-width="100px" :rules="rules">
        <el-form-item label="目标对象："> 已选择 {{ smsForm.num }} 人 </el-form-item>
        <el-form-item label="任务名称：" prop="taskName">
          <el-input
            v-model="smsForm.taskName"
            placeholder="请输入任务名称"
            :style="{ width: '50%' }"
          />
        </el-form-item>
        <el-form-item label="短信模板：" prop="templateCode">
          <el-select
            v-model="smsForm.templateCode"
            placeholder="请选择短信模板"
            :style="{ width: '50%' }"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="短信内容：" v-if="smsForm.templateCode">
          <div>{{ templateContent }}</div>
        </el-form-item>
        <el-form-item v-if="smsForm.slotList && smsForm.slotList.length > 0" label="变量配置：">
          <view style="display: flex; flex-direction: column; row-gap: 0.5rem">
            <el-row v-for="item in smsForm.slotList" :key="item">
              <el-col :span="9">
                <el-input :value="item" disabled />
              </el-col>
              <el-col :span="14" :offset="1">
                <el-input v-model="smsForm.slots[item]" />
              </el-col>
            </el-row>
          </view>
        </el-form-item>
        <el-form-item>
          <el-button @click="smsBroadcastPreview">预览</el-button>
          <el-button type="primary" @click="smsBroadcastSend" :loading="btnLoading"
            >立即创建</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 短信预览 -->
    <el-dialog v-model="smsPreview" title="短信预览" width="20%">
      <view class="sms-preview">
        <view class="sms-preview__tips">仅预览第一条短信内容：</view>
        <view class="sms-preview__content">{{ templateContent }}</view>
        <view class="sms-preview__count"
          >短信字数：<text class="sms-preview__count__unit">{{ templateContent.length }}</text
          >字</view
        >
        <view class="sms-preview__count"
          >预计扣除短信条数：<text class="sms-preview__count__unit">1条</text></view
        >
        <el-button class="sms-preview__close" type="primary" @click="smsPreview = false"
          >关闭</el-button
        >
      </view>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import * as smsApi from '@/mock/scrm/accountUser/index.ts'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false) // 弹窗控制
const btnLoading = ref(false)
const smsPreview = ref(false) // 短信预览
const smsFormRef = ref({})
const smsForm = reactive({
  type: '', // 类型 是否勾选了用户 val: check | uncheck
  taskName: '', // 任务名称
  slotList: [], // 变量插槽列表
  slots: {}, // 变量插槽json
  params: [], /// 外部传进来：手机号码列表 | 查询参数
  signNameJson: [], // 短信签名名称
  templateCode: '', // 短信模板CODE
  templateParamJson: [], // 短信模板参数
  // templateContent: '', // 短信模板内容
  num: 0
})
const selectOptions = ref([]) // 短信模板列表
const rules = reactive({
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  templateCode: [{ required: true, message: '请选择短信模板', trigger: 'blur' }]
})

const emits = defineEmits('sended')

/** 打开弹窗 */
const open = async (type: 'check' | 'uncheck', params: string[], num: number) => {
  resetSmsForm() // 重置数据
  smsForm.num = num
  smsForm.params = params
  // 获取模板列表
  selectOptions.value = await getSmsTemplate()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 获取模板列表
const getSmsTemplate = async () => {
  let res = await smsApi.getSmsTemplate()
  let result = res.list.map((item) => {
    item['label'] = item.name
    item['value'] = item.code
    return item
  })
  return result
}

// 模板内容
const templateContent = computed(() => {
  // 更新模板内容
  let content = ''
  // selectOptions.value.forEach((item) => {
  //   if (item.value == smsForm.templateCode) {
  //     content = item.content
  //   }
  // })
  // // 根据模板内容更新插槽
  // if (smsForm.slotList.length == 0) smsForm.slotList = getSmsTemplateSlots(content)
  // if (smsForm.slots && Object.keys(smsForm.slots).length > 0) content = bindTemplate(content)
  return content
})

// 获取短信模板插槽
const getSmsTemplateSlots = (template) => {
  const slots = []
  const slotPattern = /\${(.+?)\}/g
  while (true) {
    const match = slotPattern.exec(template)
    if (!match) break
    const slot = match[1]
    slots.push(slot)
  }
  return slots
}

// 简单替换模板字符串
const bindTemplate = (value) => {
  let result = value
  const slotPattern = /\${(.+?)\}/g
  while (true) {
    const match = slotPattern.exec(value)
    if (!match) break
    const slot = match[1]
    result = result.replace(`\${${slot}}`, smsForm.slots[slot] || `\${${slot}}`)
  }
  return result
}

// 短信预览
const smsBroadcastPreview = () => {
  if (templateContent.value == '') {
    ElMessage.error('请先选择短信模板')
    return
  }
  smsPreview.value = true
}

// 根据模板code更新模板签名列表
const updateSignNameList = async (templateCode: string, num: number) => {
  const templateItem = selectOptions.value.find((item) => item.code === templateCode)
  if (templateItem) {
    smsForm.signNameJson = new Array(num).fill(templateItem.type)
  }
}

// 根据插槽json和插槽列表，组装templateParamJson列表
const updateTemplateParamJson = () => {
  smsForm.templateParamJson = []
  smsForm.slotList.forEach((item) => {
    let obj = {}
    obj[item] = smsForm.slots[item]
    smsForm.templateParamJson.push(obj)
  })
}

// 重置smsForm数据
const resetSmsForm = () => {
  smsForm.taskName = ''
  smsForm.slotList = []
  smsForm.slots = {}
  smsForm.params = []
  smsForm.signNameJson = []
  smsForm.templateCode = ''
  smsForm.templateParamJson = []
  smsForm.num = 0
  smsForm.type = 'uncheck'
}

// 短信发送
const smsBroadcastSend = async () => {
  if (!smsFormRef.value) return
  await smsFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (Object.keys(smsForm.slots).length != smsForm.slotList.length) {
        ElMessage.error('请完整填写模板变量！')
        return
      }
      let params = null
      btnLoading.value = true

      // 处理短信的插槽json格式
      updateTemplateParamJson()

      if (smsForm.type == 'check') {
        // 处理短信签名
        updateSignNameList(smsForm.templateCode, smsForm.num)
        // 请求参数
        params = {
          taskName: smsForm.taskName,
          phoneNumberJson: smsForm.params,
          signNameJson: smsForm.signNameJson,
          templateCode: smsForm.templateCode,
          templateParamJson: smsForm.templateParamJson
        }
      } else if (smsForm.type == 'uncheck') {
        // 处理短信签名
        updateSignNameList(smsForm.templateCode, 1)
        // 请求参数
        params = {
          taskName: smsForm.taskName,
          queryParams: smsForm.params,
          signNameJson: smsForm.signNameJson,
          templateCode: smsForm.templateCode,
          templateParamJson: smsForm.templateParamJson
        }
      }
      // 发送短信
      if (smsForm.type == 'check') {
        await smsApi.sendBatchSmsFromUser(params)
      } else if (smsForm.type == 'uncheck') {
        await smsApi.sendBatchSmsFromQuery(params)
      }

      ElMessage.success('短信发送成功！')
      btnLoading.value = false
      dialogVisible.value = false
      emits('sended')
    } else {
      ElMessage.error('请完整填写信息！')
    }
  })
}
</script>

<style scoped lang="scss">
.sms-preview {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  &__tips {
    margin-bottom: 0.5rem;
    color: #999;
  }

  &__content {
    width: 100%;
    padding: 0.5rem;
    margin-bottom: 1rem;
    border: 1px solid #ccc;
    border-radius: 0.25rem;
    font-size: 1rem;
    line-height: 1.5;
    box-sizing: border-box;
  }

  &__count {
    align-self: flex-end;

    &__unit {
      color: #f56c6c;
    }
  }

  &__close {
    align-self: center;
    margin-top: 1rem;
  }
}
</style>
